import requests
import random
import json
import time
from MySqlClient import MysqlClient

baseUrl = "https://lucky.nocode.com"
headers = {
    "referer": "https://servicewechat.com/wx01bb1ef166cd3f4e/242/page-frame.html",
    "User-Agent": "Mozilla/5.0 (Linux; Android 9; ONEPLUS A5000 Build/PKQ1.180716.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.158 Mobile Safari/537.36 MicroMessenger/6.7.3.1360(0x2607033C) NetType/WIFI Language/zh_CN Process/appbrand2",
    # 自己用Fiddle抓包找
    "sign": "7d056deeb002246a889f1e4a720e8608b1d70174",
    "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMTU4NzY0OTAsImlhdCI6MTU0NTY1ODQxMSwiZXhwIjoxNTQ2MjYzMjExfQ.e_IIS8wfNGF2vI-A9w938zBwivcPt8tZz5YfxuzhAFM",
}
proxies = {
}
name = ''


class Award(object):
    def __init__(self):
        self.baseUrl = baseUrl
        self.headers = headers
        self.proxies = proxies
        self.name = name


    def add_proxy(self):
        mysql=MysqlClient()
        proxies['http'] = mysql.random_proxy()

    def get_random(self):
        random_url = "https://lucky.nocode.com/lottery/get_random"
        get = requests.get(random_url, headers=headers, proxies=self.proxies)
        print(get.text)
        full = str(get.json().get("links"))
        nextUrl = full[full.index('next') + 8:len(full) - 2]
        print(baseUrl + nextUrl)
        return baseUrl + nextUrl

    def get_join_url(self, url):
        result = requests.get(url, headers=headers, proxies=self.proxies)
        try:
            json_dict = json.loads(result.text)
            goods_list = json_dict['data']['prizes']['data']
            for list in goods_list:
                name_ = list['name']
                print("商品-", name_)
                self.name = str(name_)
                print(self.name, '--' + str(name_))
        except:
            print("获取商品error")
        id = result.json().get("data").get("id")
        # print("id=", id)
        join_url = 'https://lucky.nocode.com/lottery/' + id + '/join'
        return join_url

    def join(self, url):
        result = requests.post(url, headers=headers, proxies=proxies)
        print(result.text)
        if result.status_code == 200:
            print("参与成功")
            client = MysqlClient()
            client.add_award(self.name)

    def start_award(self):
        self.add_proxy()
        print(self.proxies)
        random_url = self.get_random()
        join_url = self.get_join_url(random_url)
        self.join(join_url)


if __name__ == '__main__':
    for i in range(0, 2):
        award = Award()
        award.start_award()
        time.sleep(15)
